import { listByUserIdUsingGet } from "@/services/novel-web/novelController";
import { MessageError } from "@/utils/commonUtils";
import {  BookOutlined, HeartOutlined, UserOutlined } from "@ant-design/icons";
import { history, useParams } from "@umijs/max";
import { Avatar, Card, Col, Layout, List, Menu } from "antd";
import Meta from "antd/es/card/Meta";
import { Content } from "antd/es/layout/layout";
import Sider from "antd/es/layout/Sider";
import { useEffect, useState } from "react";

import { listCollectByUserIdUsingGet } from "@/services/novel-web/collectController";
import { getUserInfoByIdUsingGet } from "@/services/novel-web/userController";
import styles from './index.less';



const UserDetail: React.FC = () =>{

  // url :id -> userId
  const {id:userId} = useParams<{id:string}>();
  // info
  const [info,setInfo] = useState<API.UserVO>();
  const loadInfo = async (userId:number)=>{
    try {
      const resp = await getUserInfoByIdUsingGet({
        id: userId,
      })
      setInfo(resp.data)
    } catch (error) {
      MessageError(error);
    }
  }
  useEffect(()=>{
    loadInfo(Number(userId));
  },[userId])

  // posts
  const [posts,setPosts] = useState<API.NovelVO[]>([]);
  const loadPosts = async (userId:number)=>{
    try {
      const resp = await listByUserIdUsingGet({
        userId: userId,
      });
      setPosts(resp.data ?? []);

    } catch (error) { 
      MessageError(error);
    }
  };

  // collects
  const [collects,setCollects] = useState<API.NovelVO[]>([]);
  const loadCollects = async (userId:number) => {
    try {
      const resp = await listCollectByUserIdUsingGet({
        userId: userId,
      });

      setCollects(resp.data ?? []);
    } catch (error) {
      MessageError(error);
    }
  };

  const handleNovelClick = (novelId:number) =>{
    history.push(`/novel/${novelId}`);
  }

  // render tabs menu
  const [selectedMenu, setSelectedMenu] = useState('posts'); // 当前选中的菜单项
 
  // lazy load datas
  useEffect(()=>{
    switch (selectedMenu) {
      case 'posts':
        loadPosts(Number(userId));
        break;
      case 'favorites':
        loadCollects(Number(userId));
        break;
      default:
        break;
    }
  },[selectedMenu])


  const menuItems = [
    {
      key: 'posts',
      icon: <BookOutlined />,
      label: 'TA的作品',
    },
    {
      key: 'favorites',
      icon: <HeartOutlined />,
      label: 'TA的收藏',
    },
    {
      key: 'profile',
      icon: <UserOutlined />,
      label: '个人资料',
    },
    // {
    //   key: 'settings',
    //   icon: <SettingOutlined />,
    //   label: '设置',
    // },
  ];

  // 根据选中的菜单项渲染内容
  const renderContent = () => {
    switch (selectedMenu) {
      case 'profile':
        return (
          <Card>
            <Meta
              avatar={<Avatar size={64} src={info?.avatar} />}
              title={info?.nickname}
              description={''}
            />
            <div style={{ marginTop: '16px' }}>
              <div></div>
              <br/>
              <div></div>
            </div>
          </Card>
        );
      case 'posts':
        return (
          <List
            grid={{column: 7}}
            dataSource={posts}
            renderItem={(item)=>(
              <Col className={styles.item}
                onClick={()=>handleNovelClick(item.id ?? -1)}
              >
                <img src={item.cover} className={styles.cover}/>
                <div className={styles.text}>{item.name}</div>
              </Col>
            )}
          />
        );
      case 'favorites':
        return (
          <List
            grid={{column: 7}}
            dataSource={collects}
            renderItem={(item)=>(
              <Col className={styles.item}
                onClick={()=>handleNovelClick(item.id ?? -1)}
              >
                <img src={item.cover} className={styles.cover}/>
                <div className={styles.text}>{item.name}</div>
              </Col>
            )}
          />
        );
      case 'settings':
        return <div>设置内容...</div>;
      default:
        return null;
    }
  };

  return (
    <Layout style={{ minHeight: '100vh' }}>
  
    <Layout>
      {/* 侧边栏导航菜单 */}
      <Sider width={200} style={{ background: '#fff' }}>
        <Menu
          mode="inline"
          selectedKeys={[selectedMenu]}
          onClick={({ key }) => setSelectedMenu(key)}
          items={menuItems}
        />
      </Sider>

      {/* 内容区域 */}
      <Content style={{ padding: '12px', background: '#f0f2f5' }}>
        <div style={{ background: '#fff', padding: '24px', minHeight: '280px' }}>
          {renderContent()}
        </div>
      </Content>
    </Layout>
  </Layout>
  );
};





export default UserDetail;